/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pv168.uloha3.swing.workers;

import cz.muni.fi.pv168.uloha3.common.DBUtils;
import cz.muni.fi.pv168.uloha3.entities.Owner;
import cz.muni.fi.pv168.uloha3.entities.Ownership;
import cz.muni.fi.pv168.uloha3.entities.RealEstate;
import cz.muni.fi.pv168.uloha3.exceptions.OwnershipManagerException;
import cz.muni.fi.pv168.uloha3.managers.OwnerManager;
import cz.muni.fi.pv168.uloha3.managers.OwnershipManager;
import cz.muni.fi.pv168.uloha3.managers.RealEstateManager;
import cz.muni.fi.pv168.uloha3.managers.impl.OwnerManagerImpl;
import cz.muni.fi.pv168.uloha3.managers.impl.OwnershipManagerImpl;
import cz.muni.fi.pv168.uloha3.managers.impl.RealEstateManagerImpl;
import cz.muni.fi.pv168.uloha3.swing.OwnershipsTableModel;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import javax.swing.SwingWorker;

/**
 *
 * @author stefan
 */
public class OwnershipListSwingWorker extends SwingWorker<Set<Ownership>, Object> {
    
    private final Owner owner;
    private final RealEstate estate;
    private final OwnershipsTableModel model;
    
    public OwnershipListSwingWorker(Owner owner, OwnershipsTableModel model) {
        this.owner = owner;
        this.model = model;
        this.estate = null;
    }
    
    public OwnershipListSwingWorker(RealEstate estate, OwnershipsTableModel model) {
        this.estate = estate;
        this.model = model;
        this.owner = null;
    }

    @Override
    protected Set<Ownership> doInBackground() throws Exception {
        Set<Ownership> retval = new HashSet<Ownership>();
        
        DataSource dataSource = DBUtils.initConnector();
        
        OwnerManager managerOwner = new OwnerManagerImpl();
        managerOwner.setDataSource(dataSource);
        
        RealEstateManager managerRealEstate = new RealEstateManagerImpl();
        managerRealEstate.setDataSource(dataSource);
        
        OwnershipManager managerOwnership = new OwnershipManagerImpl();
        managerOwnership.setDataSource(dataSource);
        managerOwnership.setOwnerManager(managerOwner);
        managerOwnership.setRealEstateManager(managerRealEstate);
        
        model.clearAllOwnerships();

        try {
            if(null != owner) {
                retval.addAll(managerOwnership.getOwnershipsByOwner(owner));
            } else {
                retval.addAll(managerOwnership.getOwnershipsByRealEstate(estate));
            }
        } catch (OwnershipManagerException ex) {
            Logger.getLogger(EstateListAllSwingWorker.class.getName()).log(Level.SEVERE, null, ex);
            return retval;
        }
        
        model.addAllOwnerships(retval);
        return retval;
    }
}
